class Local(object):
    def __init__(self):
        # self.storage = {}  # 会执行Local中的setattr产生递归故不可用

        # 利用object中的setattr进行init，从而避免递归
        object.__setattr__(self, "storage", {})

    def __setattr__(self, key, value):
        # print(key, value)
        self.storage[key] = value

    def __getattr__(self, item):
        return self.storage.get(item)


locals = Local()
locals.x1 = 123  # Local中没有x1，故执行setattr
locals.x2 = 234
locals.x3 = 345
print(locals.x2)  # 执行getattr
print(locals.__dict__)

##############################################

# class Foo(object):
#     def __setattr__(self, key, value) -> None:
#         print(key, value)  # x 123

#     def __getattr__(self, item):
#         print(item)  # x


# obj = Foo()
# obj.x = 123  # Foo中没有x，调用setattr
# obj.x
